﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.Threading;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Diagnostics;

namespace tomvangaever.CorrelationWebPart
{
    public class SPCorelationIDService
    {
        public static DataView GetLogs(Guid correlationId)
        {
            DataView uls = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPCorelationIDService service = new SPCorelationIDService();
                uls = service.GetLogsByCorrelationId(correlationId, SPUtility.GetGenericSetupPath("LOGS"));
            });
            return uls;
        }

        public DataView GetLogsByCorrelationId(Guid correlationId,string logfolder)
        {
            DataView uls = null;
            DirectoryInfo ulsdir = new DirectoryInfo(logfolder);
            if (!ulsdir.Exists) throw new ArgumentException("The system was unable to locate folder '"+logfolder+"'");
            string[] ulsfiles = ulsdir.GetFiles("*.log").Select(u => u.FullName).ToArray();
            uls = OpenFile(ulsfiles);
            uls.RowFilter = "Correlation = '" + correlationId + "'";
            return uls;
        }

        public DataView OpenFile(string[] fileNames)
        {
            DataTable data = null;
            foreach (string fileName in fileNames)
            {

                ULSHelper lp = new ULSHelper();
                DataTable temp = lp.BuildDataTable(fileName);
                if (data == null) data = temp;
                else data.Merge(temp);
            }
            DataView view = new DataView(data);
            return view;
        }

    }
}
